
import json
import requests
import firebase_admin
from firebase_admin import auth
from fastapi.encoders import jsonable_encoder
from datetime import timedelta

from odoo.modules.module import get_module_path
from odoo.addons.web_api.basemodels.vo.common.sec_level import User
from odoo.addons.basic_configuration.functions.common_utils_fc import CommonUtils
from odoo.addons.basic_configuration.functions.rp_redis_utils import RedisUtils
from odoo.addons.fastapi_odoo_bridge.core.token import JWTUtils
from odoo.addons.web_api.functions.login import Login

# 创建JWT集成对象
jwt_utils = JWTUtils(model='rp.customer')
# 创建crypt_context对象
jwt_utils.create_crypt_context()

# 初始化firebase链接
module_path = get_module_path('google_auth_login')
try:
    path = module_path + "\\static\\json\\serviceAccount.json"
    cred = firebase_admin.credentials.Certificate(path)
except:
    path = module_path + "/static/json/serviceAccount.json"
    cred = firebase_admin.credentials.Certificate(path)
default_app = firebase_admin.initialize_app(cred)


class Google_Login_func():
    
    def __init__(self, env):
        self.env = env
        
    # Google OAth验证配置
    def get_config_parameter(self):
        flag = True
        client_id = self.env['ir.config_parameter'].sudo().get_param('google_auth_login.rp_google_client_id')
        client_secret = self.env['ir.config_parameter'].sudo().get_param('google_auth_login.rp_google_client_secret')
        redirect_uri = self.env['ir.config_parameter'].sudo().get_param('google_auth_login.rp_google_redirect_uri')
        if not client_id or not client_secret or not redirect_uri:
            flag = False
        return flag, client_id, client_secret, redirect_uri

    # Google 根据access_token获取用户信息
    def google_get_user_info(self, access_token):
        url = "https://www.googleapis.com/oauth2/v2/userinfo?access_token={}".format(access_token)
        user_info = requests.get(url)
        user_info_dict = json.loads(user_info.text)
        return user_info_dict
    
    # firebase 根据access_token获取用户信息
    def firebase_get_user_info(self, access_token):
        user_info = auth.verify_id_token(access_token)
        return user_info
    
    # 获取后台用户信息
    def rectaparcel_get_user_info(self, user_info_dict):
        rp_customer = self.env['rp.customer'].sudo().search([('google_email', '=', user_info_dict['email'])])
        if not rp_customer:
            password = jwt_utils.encrypt_password(plain_password=user_info_dict['email'])
            complete_name = user_info_dict['name'].split(" ")
            rp_customer = self.env['rp.customer'].sudo().create([{
                'first_name': complete_name[1] if len(complete_name) == 2 else '',
                'last_name': complete_name[0] if len(complete_name) > 1 else '',
                'username': user_info_dict['email'],
                'email': user_info_dict['email'],
                'password': password,
                'google_email': user_info_dict['email']
            }])
        encode_jwt = jwt_utils.created_access_token(rp_customer.id, timedelta(minutes=1800))
        user = User(__from_odoo=rp_customer, __env=self.env)
        return encode_jwt, user

    # Google用户登录
    def google_login(self, user_info_dict):
        encode_jwt, user = self.rectaparcel_get_user_info(user_info_dict)
        # 生成随机序列
        md5_hex = CommonUtils().gene_random_sequence()
        # 获取Redis客户端
        redis_client = RedisUtils(db=15)
        class_result = {'access_token':encode_jwt, 'user':user}
        dict_result = jsonable_encoder(class_result)
        str_result = json.dumps(dict_result, ensure_ascii=False)
        redis_client.add_str(md5_hex, str_result)
        url = 'https://www.rectaparcel.com/?db=google_login&redis_key={md5_hex}'
        return url
    
    # google邮箱发送验证码
    def google_mail_send_code(self, act_one, mail):
        result = Login(self.env).send_mail_verify(act_one=act_one, mail=mail)
        return result
    
    # google邮箱验证码验证
    def google_mail_code_verify(self, mail, verifyt_code, rp_customer_id):
        result = Login(self.env).verify_mail_code(mail=mail, verifyt_code=verifyt_code)
        if result.get('code') == 200:
            rp_customer = self.env['rp.customer'].sudo().search([('google_email','=',mail)])
            if not rp_customer:
                rp_customer = self.env['rp.customer'].sudo().browse(rp_customer_id)
                rp_customer.write({
                    'google_email': mail
                })
            else:
                result = {
                    'code': 400,
                    'message': '该邮箱已被绑定'
                }
        return result
    